const app = getApp()
import { endpoint } from '../../utils/util.js';
const defaultAvatarUrl = 'https://wechat.larwas.com/0.png'
var userInfo = wx.getStorageSync('userInfo');

Page({
  data: {
    avatarUrl: userInfo.length !== 0 ? userInfo.avatarUrl : defaultAvatarUrl,
    theme: wx.getSystemInfoSync().theme,
    nickName: userInfo.nickName ?? ''
  },
  onLoad() {
    wx.onThemeChange((result) => {
      console.log(userInfo)
      this.setData({
        theme: result.theme,
        avatarUrl: userInfo.length !== 0 ? userInfo.avatarUrl : defaultAvatarUrl,
        nickName: userInfo.nickName ?? ''
      })
    })
  },

  onLogout(){
    console.log('登出')
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    app.globalData.hasUserInfo = false
    this.setData({
      userInfo: {},
      hasUserInfo: false,
    })
    wx.showToast({
      title: '退出成功!',
      icon: "success",
      duration: 2000
   })
   setTimeout(function () {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }, 1000)
  
  },
  onChooseAvatar(e) {
    console.log("头像："+ e.detail.avatarUrl)
    const { avatarUrl } = e.detail 
    this.setData({
      avatarUrl
    })
    var userInfo = wx.getStorageSync('userInfo')
    userInfo.avatarUrl = avatarUrl
    wx.setStorageSync('userInfo', userInfo)
  },
  submit(e) {
   var that = this;
   console.log(e.detail.value.nickname)
   app.apiRequest({
    url: endpoint.updateUser,
    method: 'POST',
    data: {
      "nickName": e.detail.value.nickname,
      "avatar": that.data.avatarUrl
    },
    success: res => {
      var userInfo = wx.getStorageSync('userInfo')
      console.log(userInfo)
      userInfo.nickName = e.detail.value.nickname
      wx.setStorageSync('userInfo', userInfo)
      wx.navigateBack();
    },
    fail: res =>{
      wx.showToast({
        title: '服务异常，请稍后再试',
        icon: 'none'
      })
    }
  })
  }
})
